package me.keiwu.admin.service.impl;

import me.keiwu.admin.dao.ConfigDao;
import me.keiwu.admin.domain.config.Config;
import me.keiwu.admin.service.ConfigService;
import me.keiwu.pub.data.ConfigType;
import me.keiwu.pub.util.CacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;

/**
 * Created by kei on 27/11/2017.
 */
@Transactional
@Service
public class ConfigServiceImpl implements ConfigService {

    @Autowired
    private ConfigDao configDao;
    @Autowired
    private CacheUtil cacheUtil;

    @PostConstruct
    public void initConfig() {
        configDao.findAll().forEach(c -> {
            if (c != null) {
                cacheUtil.setConfig(c.getConfigType(), c.getConfigJson());
            }
        });
    }


    @Override
    public Config getConfig(ConfigType configType) {
        return this.getConfig(configType.getType());
    }

    @Override
    public Config getConfig(Integer configType) {
        return configDao.findOne(configType);
    }


    @Override
    public Config setConfig(Config config) {
        config = configDao.save(config);
        cacheUtil.setConfig(config.getConfigType(), config.getConfigJson());
        return config;
    }

    @Override
    public Iterable<Config> getAllConfig() {
        return configDao.findAll();
    }
}
